package com.home.demo.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.home.demo.entity.ChatHistoryEntity;
import com.home.demo.service.ChatHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{uid}")
public class WebSocketController {

    static ChatHistoryService chatHistoryService;

    @Autowired
    private void setChatHistoryService(ChatHistoryService chatHistoryService){
        this.chatHistoryService = chatHistoryService;
    }



    //用来存储连接数
    private static AtomicInteger onlineSessionClientCount = new AtomicInteger(0);

    //用来存储会话
    private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();

    private String id;



    /**
     * 连接会话
     * @param uid
     * @param session
     * @throws IOException
     */
    @OnOpen
    public void onOpen(@PathParam("uid") String uid, Session session) throws IOException {
        //判断该用户是否存在会话, 如果存在的话删除旧的会话
        if (onlineSessionClientMap.containsKey(uid)) {
            onlineSessionClientMap.get(uid).close();
        }
        //存储新的会话
        onlineSessionClientMap.put(uid, session);
        //连接数增加
        onlineSessionClientCount.incrementAndGet();
        this.id = uid;
        log.info("连接建立中 --> session_id= {},uid={},当前在线人数={}", session.getId(), uid, onlineSessionClientCount);
        log.info("当前session_Id={}", onlineSessionClientMap.get(uid).getId());



    }

    /**
     * 删除会话
     * @param uid
     * @param session
     */
    @OnClose
    public void onClose(@PathParam("uid") String uid, Session session) {
        log.info("当前session_Id={}", onlineSessionClientMap.get(uid).getId());
        onlineSessionClientMap.remove(uid);
        onlineSessionClientCount.decrementAndGet();
        log.info("连接建立中 --> session_id= {},uid={},当前在线人数={}", session.getId(), uid, onlineSessionClientCount);
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Throwable err, Session session) {
        log.error("WebSocket发生错误，错误信息为：" + err.getMessage());
        err.printStackTrace();
    }

    /**
     * 发送&&接收消息
     * @param mes
     * @param session
     */
    @OnMessage
    public void onMes(String mes, Session session) throws IOException, EncodeException {
       ChatHistoryEntity chatHistoryEntity = JSON.parseObject(mes, ChatHistoryEntity.class);

//        ChatHistoryEntity chatHistoryEntity=jsonObject.getObject("chatHistoryEntity",ChatHistoryEntity.class);
            sendToOne(chatHistoryEntity);



    }

    private void sendToOne(ChatHistoryEntity chatHistoryEntity) throws IOException, EncodeException {
        Session session = onlineSessionClientMap.get(chatHistoryEntity.getReceiveId());
        chatHistoryEntity.setStatus(0);
        chatHistoryEntity.setCreateTime(new Date());
        if (session!=null) {
            session.getBasicRemote().sendText(JSONObject.toJSONString(chatHistoryEntity));
        }
        chatHistoryService.save(chatHistoryEntity);


    }


}
